package com.jy.modules.cims.component.api;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.JResult;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.ExceptionUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.component.common.service.TCMmCreditDetailService;
import com.jy.modules.cims.component.creditRight.ICCreditRight;
import com.jy.modules.cims.component.sysAssist.JieYueApiAssist;
import com.jy.modules.cims.data.common.dao.TCMmCreditDetailDao;
import com.jy.modules.cims.data.common.dto.TCMmCreditDetailDTO;
import com.jy.modules.cims.data.dao.DealDao;
import com.jy.modules.cims.data.interact.api.ResponseMessageEnum;
import com.jy.modules.cims.data.interact.api.request.RequestCreditRedemptionApplyDTO;
import com.jy.modules.cims.data.interact.api.request.RequestCreditRedemptionListDTO;
import com.jy.modules.cims.data.interact.api.request.RequestTransferResultReceiveDTO;
import com.jy.modules.cims.data.interact.api.request.TransferCreidtReceiveDTO;
import com.jy.modules.cims.data.interact.api.response.ResponseCreditRedemptionApplyDTO;
import com.jy.modules.cims.data.interact.api.response.ResponseTransferResultReceiveDTO;

/**
 * @description 捷越接受外围系统债权业务处理组件。
 * @author shengzhoutao
 * 
 */
@Service("com.jy.modules.cims.component.api.CReceiveCreditImpl")
public class CReceiveCreditImpl {
	
	private static final Logger logger = LoggerFactory.getLogger(CReceiveCreditImpl.class);
	
	@Autowired
	public DealDao dealDao;
	
	@Autowired
	private TCMmCreditDetailDao tcmmcreditDetailDao;
	
	
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.JieYueApiAssist")
	private JieYueApiAssist jieYueApiAssist;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.creditRight.CCreditRightImpl")
	protected ICCreditRight creditRight;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditDetailService")
	private TCMmCreditDetailService creditDetailService;
	
	/**
	 * @description 接受商户推送推送债权审批结果(债权转让结果)， 同时生成响应结果反馈给商户 。
	 * @param
	 * @return
	 * @throws Exception
	 * @author
	 * @Date
	 */
	public ResponseTransferResultReceiveDTO dealTransferResult(final RequestTransferResultReceiveDTO content) throws Exception {
		ResponseTransferResultReceiveDTO response = new ResponseTransferResultReceiveDTO();

		try {
			List<TransferCreidtReceiveDTO> creditList = content.getCreditList();
			
			// 验证债权转让
			JResult jResult = validateTransferResult(creditList);
			if (jResult.isSuccess() == false) {
				response.setResult(ResponseMessageEnum.FAILURE.getResult());
				response.setMessage(jResult.getErrMsg());
				return response;
			}
			
			TCMmCreditDetailDTO creditDetailDTO = null;
			for (TransferCreidtReceiveDTO requestTransferCreidtDTO : creditList) {
				String creditEachStatus = requestTransferCreidtDTO.getCreditEachStatus();
				if (CimsConstant.CREDIT_STATUS_WIN.equals(creditEachStatus)) {
					logger.info("债权转让编号：【{}】审批通过！", requestTransferCreidtDTO.getTransferId());
					
					dealDao.updateCreditDealDetailByInterface(SearchParamUtil.getSearchParam(requestTransferCreidtDTO));
				} else if (CimsConstant.CREDIT_STATUS_LOSE.equals(creditEachStatus)) {
					logger.info("债权转让编号：【{}】审批拒绝！", requestTransferCreidtDTO.getTransferId());

                    creditDetailDTO = new TCMmCreditDetailDTO();
					creditDetailDTO.setCreditCode(requestTransferCreidtDTO.getCreditCode());
					creditDetailDTO.setTransferId(requestTransferCreidtDTO.getTransferId());
					creditDetailDTO.setCreditSource(CimsConstant.CREDIT_SOURCE_CRE);
					List<TCMmCreditDetailDTO> creditDetailList = creditDetailService.searchTCMmCreditDetail(SearchParamUtil.getSearchParam(creditDetailDTO));
					if (CollectionsUtils.isEmpty(creditDetailList)) {
						continue;
					}
					creditDetailService.batchUpdateTCMmCreditStatus(creditDetailList.get(0).getId().toString(), CimsConstant.CREDIT_STATUS_LOSE);
				} else if (CimsConstant.CREDIT_STATUS_WAY.equals(creditEachStatus)) {
					logger.info("债权转让编号：【{}】正在审批中！", requestTransferCreidtDTO.getTransferId());
				}
			}
			
			response.setId("TR" + DateTimeUtils.formatDate(new Date(), DateTimeUtils.DEFAULT_DATE_TIME_FORMAT_2));
			response.setResult(ResponseMessageEnum.SUCCESS.getResult());
			response.setMessage(ResponseMessageEnum.SUCCESS.getMessage());
		} catch (Exception e) {
			response.setResult(ResponseMessageEnum.FAILURE.getResult());
			response.setMessage("接收审批结果处理失败！" + e.getMessage());
			logger.error("接收审批结果处理失败：" + ExceptionUtils.getStackTraceAsString(e));
		}
		
		return response;
	}

	/**
	 * @description 接受商户债权赎回申请请求
	 * @param
	 * @return
	 * @throws Exception
	 * @author
	 * @Date
	 */
	public ResponseCreditRedemptionApplyDTO applyRedemption(final RequestCreditRedemptionApplyDTO content) throws Exception {

		logger.info("债权赎回申请开始>>！");
		ResponseCreditRedemptionApplyDTO response = new ResponseCreditRedemptionApplyDTO();
		List<RequestCreditRedemptionListDTO> list = content.getCreditList();
		//验证数据
		JResult result = validateRedemption(list);
		if(result.isSuccess() == false){
			response.setResult(ResponseMessageEnum.FAILURE.getResult());
			response.setMessage(result.getErrMsg());
			return response;
		}
		//债权赎回申请
		String dealCode = creditRight.doReceiveCreditRedemption(list);
		response.setId(dealCode);// 申请成功返回的回购申请编号，该字段唯一.
		response.setResult(ResponseMessageEnum.SUCCESS.getResult());
		response.setMessage("赎回申请申请交易成功！回购申请编号为:" + dealCode);
		return response;
	}
	
	/**
	 * 赎回校验
	 * @author zhangmi
	 * @date  2017年1月13日
	 * @param creditList
	 * @return
	 */
	private JResult validateRedemption(List<RequestCreditRedemptionListDTO> creditList){
		JResult result = new JResult();
		result.setSuccess(false);
		if(CollectionsUtils.isEmpty(creditList)){
			result.setErrCode(ResponseMessageEnum.FAILURE.getResult());
			result.setErrMsg("债权赎回列表为空！");
			return result;	
		}
		if(creditList.size()>1000){
			result.setErrCode(ResponseMessageEnum.FAILURE.getResult());
			result.setErrMsg("债权赎回列表不能超过1000条！");
			return result;	
		}
		
		//为空检验
		String error = null;
		for (RequestCreditRedemptionListDTO requestCreditDTO : creditList) {
			error = jieYueApiAssist.validate(requestCreditDTO);
		}
		if (StringUtils.hasText(error)) {
			result.setErrMsg(error);
			return result;
		}
		StringBuffer sb = new StringBuffer();
		
		for (RequestCreditRedemptionListDTO requestCreditDTO : creditList) {
			TCMmCreditDetailDTO searchDto = new TCMmCreditDetailDTO();
			searchDto.setTransferId(requestCreditDTO.getTransferId());
			searchDto.setCreditCode(requestCreditDTO.getCreditCode());
			List<TCMmCreditDetailDTO> list = tcmmcreditDetailDao.searchTCMmCreditDetail(SearchParamUtil.getSearchParam(searchDto));
			if(CollectionsUtils.isEmpty(list)){
				sb.append(java.text.MessageFormat.format("该债权转让编号[{0}]不存在;", new Object[] { requestCreditDTO.getTransferId() }));
			}else{
				searchDto = list.get(0);
				if(!CimsConstant.CREDIT_STATUS_WIN.equals(searchDto.getCreditorStatus())){
					sb.append(java.text.MessageFormat.format("该债权转让编号[{0}]状态为[{1}]，不符合赎回状态！;", new Object[] {requestCreditDTO.getTransferId() ,searchDto.getCreditorStatus() }));
				}
				if(searchDto.getThisCreditorValue().compareTo(new BigDecimal(0))<1){
					sb.append(java.text.MessageFormat.format("该债权转让编号[{0}]债权价值为零，不能赎回！;", new Object[] { requestCreditDTO.getTransferId() }));
				}
			}
		}

		error = sb.toString();
		if (StringUtils.hasText(error)) {
			result.setErrMsg(error);
			return result;
		}
		result.setSuccess(true);
		return result;
	}
	
	/**
	 * 验证债权转让结果
	 * 
	 * @param loanList
	 * @return JResult
	 * @author shengzhoutao
	 * @throws Exception
	 */
	JResult validateTransferResult(final List<TransferCreidtReceiveDTO> creditList) throws Exception {
		JResult result = new JResult();
		result.setSuccess(false);

		if (CollectionsUtils.isEmpty(creditList)) {
			result.setErrCode(ResponseMessageEnum.FAILURE.getResult());
			result.setErrMsg("债权列表不能为空");
			return result;
		}

		if (creditList.size() > 1000) {
			result.setErrMsg("债权列表条数不能超过1000条以上");
			return result;
		}

		String error = null;
		for (TransferCreidtReceiveDTO credit : creditList) {
			error = jieYueApiAssist.validate(credit);
		}
		if (StringUtils.hasText(error)) {
			result.setErrMsg(error);
			return result;
		}

		StringBuffer sb = new StringBuffer();
		TCMmCreditDetailDTO creditDetailDTO = null;
		for (TransferCreidtReceiveDTO credit : creditList) {
			if (credit.getMakeCreditorValue().compareTo(BigDecimal.ZERO) < 1) {
				sb.append(java.text.MessageFormat.format("借款编号[{0}],债权转让编号[{1}],转让债权价值[{2}]不能小于或等于0;",
						new Object[] { credit.getCreditCode(), credit.getTransferId(), credit.getMakeCreditorValue() }));
			}

			creditDetailDTO = new TCMmCreditDetailDTO();
			creditDetailDTO.setCreditCode(credit.getCreditCode());
			creditDetailDTO.setTransferId(credit.getTransferId());
			creditDetailDTO.setCreditSource(CimsConstant.CREDIT_SOURCE_CRE);
			List<TCMmCreditDetailDTO> creditDetailList = creditDetailService.searchTCMmCreditDetail(SearchParamUtil.getSearchParam(creditDetailDTO));
			if (CollectionsUtils.isEmpty(creditDetailList)) {
				sb.append(java.text.MessageFormat.format("借款编号[{0}],债权转让编号[{1}],不存在;",
						new Object[] { credit.getCreditCode(), credit.getTransferId() }));
			} else {
				creditDetailDTO = creditDetailList.get(0);
				if (CimsConstant.CREDIT_STATUS_WIN.equals(creditDetailDTO.getCreditorStatus())) {
					sb.append(java.text.MessageFormat.format("借款编号[{0}],债权转让编号[{1}],的已经债权转让成功，不可重复债权转让;", new Object[] { credit.getCreditCode(),
							credit.getTransferId() }));
				} else {
					if (!CimsConstant.CREDIT_STATUS_WAY.equals(creditDetailDTO.getCreditorStatus())) {
						sb.append(java.text.MessageFormat.format("借款编号[{0}],债权转让编号[{1}],债权状态不符合债权转让;",
								new Object[] { credit.getCreditCode(), credit.getTransferId() }));
					}
				}
			}
		}

		error = sb.toString();
		if (StringUtils.hasText(error)) {
			result.setErrMsg(error);
			return result;
		}

		result.setSuccess(true);
		return result;
	}
}
